<template>
  <div
    :class="{ fullscreen: fullscreen }"
    :style="{ width: containerWidth }"
    class="tinymce-container"
  >
    <textarea :id="tinymceId" class="tinymce-textarea" />
    <!-- <div class="editor-custom-btn-container">
      <editorImage
        @successCBK="imageSuccessCBK"
        class="editor-upload-btn"
        color
      />
    </div> -->
  </div>
</template>

<script>
/**
 * docs:
 * https://panjiachen.github.io/vue-element-admin-site/feature/component/rich-editor.html#tinymce
 */
import editorImage from "./components/EditorImage.vue";
import plugins from "./plugins";
import toolbar from "./toolbar";
import load from "./dynamicLoadScript";

// why use this cdn, detail see https://github.com/PanJiaChen/tinymce-all-in-one
// const tinymceCDN = "https://cdn.jsdelivr.net/npm/tinymce-all-in-one@4.9.3/tinymce.min.js";
// const tinymceCDN = "plugins/tinymce4.3.3/tinymce-v4.3.3.min.js";
// const tinymceCDN = "plugins/tinymce5/tinymce/tinymce.min.js";
const tinymceCDN = "plugins/tinymce/tinymce.min.js";
import { AliOssClient } from "../../lib/oss";
export default {
  name: "Tinymce",
  components: { editorImage },
  props: {
    id: {
      type: String,
      default() {
        return (
          "vue-tinymce-" +
          +new Date() +
          ((Math.random() * 1000).toFixed(0) + "")
        );
      }
    },
    value: {
      type: String,
      default: ""
    },
    toolbar: {
      type: Array,
      required: false,
      default() {
        return [];
      }
    },
    menubar: {
      type: String,
      default: "file edit insert view format table"
    },
    height: {
      type: [Number, String],
      required: false,
      default: 360
    },
    width: {
      type: [Number, String],
      required: false,
      default: "auto"
    }
  },
  data() {
    return {
      hasChange: false,
      hasInit: false,
      tinymceId: this.id,
      fullscreen: false,
      languageTypeList: {
        // en: "en",
        // es: "es_MX",
        // ja: "ja"
        zh: "zh_CN"
      }
    };
  },
  computed: {
    containerWidth() {
      const { width } = this;
      if (/^[\d]+(\.[\d]+)?$/.test(width)) {
        // matches `100`, `'100'`
        return `${width}px`;
      }
      return width;
    }
  },
  watch: {
    value(val) {
      if (!this.hasChange && this.hasInit) {
        this.$nextTick(() =>
          window.tinymce.get(this.tinymceId).setContent(val || "")
        );
      }
    }
  },
  mounted() {
    this.init();
  },
  created() {
    if (window.tinymce) {
      this.initTinymce();
    }
  },
  destroyed() {
    this.destroyTinymce();
  },
  methods: {
    init() {
      // dynamic load tinymce from cdn
      load(tinymceCDN, err => {
        if (err) {
          this.$message.error(err.message);
          return;
        }
        this.initTinymce();
      });
    },
    initTinymce() {
      // eslint-disable-next-line no-underscore-dangle
      const _this = this;
      window.tinymce.init({
        selector: `#${this.tinymceId}`,
        language: this.languageTypeList.zh,
        height: this.height,
        body_class: "panel-body ",
        object_resizing: false,
        toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar, // false禁用工具栏（隐藏工具栏）
        plugins,

        // disabled:true, //禁用
        // menubar: this.menubar,
        menubar: false, // 隐藏、显示最上方menu菜单
        browser_spellcheck: false, // 拼写检查
        branding: false, // 隐藏、显示水印
        statusbar: true, // 隐藏、显示编辑器底部的状态栏

        powerpaste_word_import: "propmt", // 参数可以是propmt, merge, clear，效果自行切换对比
        powerpaste_html_import: "propmt", // propmt, merge, clear
        powerpaste_allow_local_images: true,
        paste_data_images: true, // 允许粘贴图像

        end_container_on_empty_block: true,
        code_dialog_height: 450,
        code_dialog_width: 1000,
        advlist_bullet_styles: "square",
        advlist_number_styles: "default",
        imagetools_cors_hosts: ["aliyuncs.com"],
        default_link_target: "_blank",
        link_title: false,
        nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
        init_instance_callback: editor => {
          _this.editor = editor;
          if (_this.value) {
            editor.setContent(_this.value);
          }
          _this.hasInit = true;
          editor.on("Change KeyUp SetContent", () => {
            this.hasChange = true;
            _this.$emit("input", editor.getContent());
          });
        },
        setup(editor) {
          editor.on("FullscreenStateChanged", e => {
            _this.fullscreen = e.state;
          });
        },
        // file_picker_callback(callback, value, meta) {
        //   console.log(11132);
        //   const input = document.createElement("input");
        //   input.setAttribute("type", "file");
        //   input.onchange = function() {
        //     const file = this.files[0];
        //     const form = new FormData();
        //   };

        //   input.click();
        // },
        // 整合七牛上传
        // images_dataimg_filter(img) {
        // console.log(img);
        // return img.hasAttribute("internal-blob");
        // setTimeout(() => {
        //   const $image = $(img)
        //   $image.removeAttr('width')
        //   $image.removeAttr('height')
        //   if ($image[0].height && $image[0].width) {
        //     $image.attr('data-wscntype', 'image')
        //     $image.attr('data-wscnh', $image[0].height)
        //     $image.attr('data-wscnw', $image[0].width)
        //     $image.addClass('wscnph')
        //   }
        // }, 0)
        // return false;
        // },
        async images_upload_handler(blobInfo, success, failure) {
          if (blobInfo.blob().size > 1024 * 500) {
            _this.handleError("上传图片尺寸不能超过500k！");
            success("");
          } else {
            const file = new window.File(
              [blobInfo.blob()],
              blobInfo.filename(),
              {
                type: blobInfo.blob().type
              }
            );
            try {
              let res = await AliOssClient.upload(file);
              // this.isUploading = false;
              // this.$emit("input", res.url);
              success(res.url);
            } catch (error) {
              failure("出现未知问题，刷新页面，或者联系程序员");
            }
            // this.$Api.Upload({ file }).then(([err, res]) => {
            //   if (err) {
            //     failure("出现未知问题，刷新页面，或者联系程序员");
            //     console.log(err);
            //   } else {
            //     console.log(res);
            //     success(res);
            //   }
            //   _this.clearBlobImages();
            // });
          }
        }
        // images_upload_url:
        //   process.env.VUE_APP_API_PREFIX_URL
        //   + process.env.VUE_APP_UPLOAD_URL
        //   + '/imgUpload'
      });
    },
    destroyTinymce() {
      const tinymce = window.tinymce.get(this.tinymceId);
      if (this.fullscreen) {
        tinymce.execCommand("mceFullScreen");
      }
      if (tinymce) {
        tinymce.destroy();
      }
    },
    setContent(value) {
      window.tinymce.get(this.tinymceId).setContent(value);
    },
    getContent() {
      window.tinymce.get(this.tinymceId).getContent();
    },
    imageSuccessCBK(arr) {
      const _this = this;
      // arr.forEach(v => {
      //   window.tinymce.get(_this.tinymceId).insertContent(`<img class="wscnph" src="${v.url}" >`)
      // })
      arr.forEach(v => {
        window.tinymce
          .get(_this.tinymceId)
          .insertContent(
            `<img class="wscnph" style="max-width:100%" src="${v}" >`
          );
      });
    }
  }
};
</script>
<style></style>
<style scoped>
.tinymce-container {
  position: relative;
  line-height: normal;
}
.tinymce-container >>> .mce-fullscreen {
  z-index: 10000;
}
.tinymce-textarea {
  visibility: hidden;
  z-index: -1;
}
.editor-custom-btn-container {
  position: absolute;
  right: 4px;
  top: 4px;
  /*z-index: 2005;*/
}
.fullscreen .editor-custom-btn-container {
  z-index: 10000;
  position: fixed;
}
.editor-upload-btn {
  display: inline-block;
}
</style>
